import { create } from "zustand";
import resetters from "@/store/resetter";
import { persist,devtools } from "zustand/middleware";
import { immer } from "zustand/middleware/immer";
import { getUserApi } from "@/api/user-api";
import to from "await-to-js";
type UserStoreType = typeof initstate

const initstate ={
    user:{} as User
}



const useUserStore = create<UserStoreType>()(
    immer(
        devtools(
            persist(
                (set)=>{
                    //重置回调函数
                    resetters.push(()=>set(initstate))
                
                    return{
                        ...initstate
                    }
                },{name:'user-store'}
            ),{name:'user-store'}
        )
    )
)



export default useUserStore


//selectors
//名字
export const selectName =(state:UserStoreType) => state.user.nickname || state.user.username
//头像
export const selectAvatar =(state:UserStoreType) => state.user.user_pic


//actions
//初始化用户基本信息
export const initUser = async () =>{
    //调用接口
    //接收信息，存储到当前store的user中
    const [err,res]=await to(getUserApi())

    if(err) return

        useUserStore.setState((state)=>{
            if(res.data){
            state.user = res.data
        }
    })
    }